﻿using Microsoft.EntityFrameworkCore;
using Npgsql;
using SovaDataService.SoModels;
using SovaDataService.SovaModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SovaDataService.SovaDataServices
{
    public class MarkedQuestionDataService
    {

        /**
         * Retrieves one marked question by given QuestionId and AccountId.
         */
        public MarkedQuestion GetOne(int questionId, int accountId)
        {
            using (var db = new DbContext())
            {
                IQueryable<MarkedQuestion> markedQuestion = db.MarkedQuestions
                    .Where( mq => mq.QuestionId == questionId && mq.AccountId == accountId)
                    .Include(mq => mq.Account)
                    .Include(mq => mq.Question);
                return markedQuestion.SingleOrDefault();
            }
        }

        /**
         * Retrieves all marked questions.
         */
        public IEnumerable<MarkedQuestion> GetMarkedQuestionsForUser(int userId)
        {
            using (var db = new DbContext())
            {
                IQueryable<MarkedQuestion> markedQuestions = db.MarkedQuestions
                    .Include(mq => mq.Account)
                    .Include(mq => mq.Question)
                    .Where(mq => mq.AccountId == userId);
                return markedQuestions.ToList();
            }
        }
        
        /**
         * Retrieves the total without having to fetch all the authors from db.
         */
        public int GetCount(int userId)
        {
            using (var db = new DbContext())
            {
                return db.MarkedQuestions.Where(mq => mq.AccountId == userId).Count();
            }
        }

        /**
         * Creates a MarkedQuestion by adding it to the database.
         */
        public MarkedQuestion Create(MarkedQuestion markedQuestion)
        {
            using (var db = new DbContext())
            {
                try
                {
                    var entry = db.MarkedQuestions.Add(markedQuestion);
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    return null;
                }

                return markedQuestion;
            }
        }

        /**
         * Deletes a MarkedQuestion by given QuestionId and AccountId.
         */
        public bool Delete(int questionId, int accountId)
        {
            using (var db = new DbContext())
            {
                var MarkedQuestion = db.MarkedQuestions
                    .SingleOrDefault(mq => mq.QuestionId == questionId && mq.AccountId == accountId);
                if (MarkedQuestion == null)
                    return false;
                db.MarkedQuestions.Remove(MarkedQuestion);
                db.SaveChanges();

                return true;
            }
        }
    }
}
